package com.motong.gongdan.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.motong.gongdan.config.wechat.WechatConfig;
import com.motong.gongdan.vo.system.common.query.WXMsgTemplate;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import java.util.Objects;

@ApiModel("微信工具类")
@Slf4j
public class WeChatUtil {

    private static String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";

    public static String  getAccessToken(WechatConfig wechatConfig) {
        Object access_token = RedisUtil.get("access_token");
        if (Objects.nonNull(access_token)){
            return access_token.toString();
        }
        String requestUrl = accessTokenUrl + "appid=" + wechatConfig.getAppid() + "&secret=" + wechatConfig.getKey();
        String resp = HttpUtil.get(requestUrl);
        cn.hutool.json.JSONObject result = JSONUtil.parseObj(resp);
        RedisUtil.set("access_token", result.getStr("access_token"), 7000);
        return result.getStr("access_token");
    }

    public static String sendMsgByTemplate(WXMsgTemplate param, String  accessToken){
        String requestUrl = " https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        String result = HttpRequest.post(requestUrl).contentType(MediaType.APPLICATION_JSON_VALUE).body(JSONUtil.toJsonStr(param)).execute().body();
        log.info(result);
        return result;
    }


}
